package com.example.administrator.view;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import butterknife.BindView;
import cn.smssdk.EventHandler;
import okhttp3.Call;
import okhttp3.Response;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.smssdk.SMSSDK;
import com.example.administrator.base.BaseActivity;
import com.example.administrator.module.UrlDefine;
import com.example.administrator.testapk.R;
import com.example.administrator.utils.NetUtils;
import com.example.administrator.utils.SpUtils;
import org.json.JSONObject;

public class AtySetPwd extends BaseActivity implements OnClickListener{

    @BindView(R.id.et_set) EditText et_set;
    @BindView(R.id.et_verify) EditText et_verify;
    @BindView(R.id.btn_sendcode) Button btn_sendcode;
    @BindView(R.id.btn_sure) Button btn_sure;
    @BindView(R.id.set_pwd_title) TitleBar set_pwd_title;

    private String phoneNumber;


    private String countryCode="86";
    private int i = 60;//倒计时

    private static final String TAG = "AtySetPwd";

    @Override
    protected int getLayoutResourceId() {
        return R.layout.aty_set_pwd;
    }

    @Override
    protected void init() {
        phoneNumber = (String) SpUtils.get(AtySetPwd.this,"phone","");
        SMSSDK.initSDK(AtySetPwd.this, UrlDefine.APP_KEY, UrlDefine.APP_SECRET);
        //initSDK方法是短信SDK的入口，需要传递您从MOB应用管理后台中注册的SMSSDK的应用AppKey和AppSecrete，如果填写错误，后续的操作都将不能进行
        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -1) {
                btn_sendcode.setText(i + " s");
            } else if (msg.what == -2) {
                btn_sendcode.setText("发送");
                btn_sendcode.setClickable(true);
                i = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("asd", "event=" + event + "  result=" + result + "  ---> result=-1 success , result=0 error");
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //构造请求参数
                        final Map<String, String> reqBody = new ConcurrentSkipListMap<>();
                        reqBody.put("searchPassword", et_set.getText().toString());
                        reqBody.put("verifyCode", et_verify.getText().toString());

                        NetUtils.getInstance().postDataAsynToNet(UrlDefine.ACTION_URL_SETSEARCHPWD, reqBody, new NetUtils.MyNetCall() {
                            @Override
                            public void success(Call call, Response response) throws IOException {
                                final String RegiMsgJsonStr = response.body().string();
                                Log.d(TAG,RegiMsgJsonStr);
                                //看是否需要使用到返回值
                            }

                            @Override
                            public void failed(Call call, IOException e) {
                                Log.e(TAG,e.getMessage());
                            }
                        });
                        toast("查询密码设置成功，请返回查询");
                        forward(AtyMain.class);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        toast("验证码已经发送");
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
                    try {
                        Throwable throwable = (Throwable) data;
                        throwable.printStackTrace();
                        JSONObject object = new JSONObject(throwable.getMessage());
                        String des = object.optString("detail");//错误描述
                        int status = object.optInt("status");//错误代码
                        if (status > 0 && !TextUtils.isEmpty(des)) {
                            Log.e("asd", "des: " + des);
                            toast(des);
                            return;
                        }
                    } catch (Exception e) {
                        //do something
                    }
                }
            }
        }
    };
    @Override
    protected void initView() {
        set_pwd_title = (TitleBar)findViewById(R.id.set_pwd_title);
        set_pwd_title.setLeftImageResource(R.mipmap.back);
        set_pwd_title.setTitle("设置查询密码");
        set_pwd_title.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_sendcode.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_sendcode:
                SMSSDK.getVerificationCode(countryCode,phoneNumber);
                btn_sendcode.setClickable(false);
                //开始倒计时
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-1);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-2);
                    }
                }).start();
                break;
            case R.id.btn_sure:
                String code = et_verify.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    Toast.makeText(getApplicationContext(), "验证码不能为空",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                SMSSDK.submitVerificationCode(countryCode, phoneNumber, code);
                break;
        }
    }
}

